package br.com.californiahotel.server.hibernate;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.classic.Session;

import br.com.californiahotel.server.hibernate.models.Apartamento;
import br.com.californiahotel.server.hibernate.models.Hospede;
import br.com.californiahotel.server.hibernate.models.Locacao;
import br.com.californiahotel.server.hibernate.models.Reserva;
import br.com.californiahotel.server.hibernate.models.Servico;
import br.com.californiahotel.server.hibernate.models.Tipo;

public class HibernateUtils {

	private SessionFactory sessionFactory;
	private Session session;

	private SessionFactory addAnnotetadeClassesAndBuilSessionFactory(AnnotationConfiguration configure) {
		configure.addAnnotatedClass(Apartamento.class);
		configure.addAnnotatedClass(Hospede.class);
		configure.addAnnotatedClass(Tipo.class);
		configure.addAnnotatedClass(Servico.class);
		configure.addAnnotatedClass(Reserva.class);
		configure.addAnnotatedClass(Locacao.class);
		return configure.buildSessionFactory();
	}

	private void openSession() {
		if(sessionFactory == null){
			sessionFactory = addAnnotetadeClassesAndBuilSessionFactory(new AnnotationConfiguration().configure());
		}
		if(session == null || !session.isOpen()){
			session = sessionFactory.openSession();
		}
	}

	private void startSession(){
		openSession();
		session.beginTransaction();
	}

	public Session getSession() {
		if(session == null || !session.isOpen()){
			startSession();
		}
		return session;
	}

	public void close() {
		session.flush();
		session.getTransaction().commit();
		session.close();
	}
}
